package com.umeox.watch.moto.launcher.widget

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.provider.Settings
import android.text.format.DateFormat
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import com.umeox.moto.common.log.Logger
import com.umeox.moto.watch.themes.util.CountDownTimer
import com.umeox.moto.watch.themes.widget.RelativeLayout
import com.umeox.moto.watch.themes.widget.TextView
import com.umeox.watch.moto.dataservice.constants.Constants
import com.umeox.watch.moto.launcher.R
import com.umeox.watch.moto.launcher.bean.PrayerTimeInfo
import com.umeox.watch.moto.launcher.utils.PrayerTimesCoordinator
import com.umeox.watch.moto.launcher.utils.Utils
import com.umeox.watch.moto.pedometer.util.CacheImpl
import com.umeox.watch.moto.pedometer.util.ICache
import java.util.Locale
import java.util.TimeZone

/**
 * Created by Rambo 2024/3/27/0027
 * Describe:
 */
class PrayerTimeView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : RelativeLayout(context, attrs, defStyleAttr) {

    private var mDownTimer: CountDownTimer? = null
    private var mPrayerTime: TextView
    private var mPrayerTimeName: TextView
    private var mPrayerTimeAmPm: TextView
    private var mPrayerTimeCount: TextView
    private var prayerTimesCoordinator: PrayerTimesCoordinator

    private var prayerTimeList: MutableList<PrayerTimeInfo>? = null

    private var is24HourFormat: Boolean = false

    init {
        val view =
            LayoutInflater.from(context).inflate(R.layout.view_prayer_time, this)
        mPrayerTime = view.findViewById(R.id.tv_prayer_time)
        mPrayerTimeCount = view.findViewById(R.id.tv_time_count)
        mPrayerTimeAmPm = view.findViewById(R.id.tv_prayer_time_am_pm)
        mPrayerTimeName = view.findViewById(R.id.tv_name)
        prayerTimesCoordinator = PrayerTimesCoordinator()
    }

    private fun initData(isShow: Boolean) {
        Logger.e("isShow=${isShow}")
        if (!isShow) {
            visibility = View.GONE
            return
        }

        if(CacheImpl.getInstance()[ICache.KEY_WATCH_FACE_ICON_INDEX, 0] > 0){
            visibility = View.GONE
            return
        }

        //获取本地经纬度
        val lat: String? = Settings.Global.getString(context.contentResolver, "LAT")
        val long: String? = Settings.Global.getString(context.contentResolver, "LONG")
        Logger.e("lat=$lat,long=$long")
        if ((!lat.isNullOrEmpty() && lat != "-999") && (!long.isNullOrEmpty() && long != "-999")) {
            calcPrayerTime(lat.toDouble(), long.toDouble())
        } else {
            prayerTimeList = null
        }
        if (prayerTimeList != null) {
            is24HourFormat = DateFormat.is24HourFormat(context)
            visibility = View.VISIBLE
            //根据当前时间
            val currentTimeMillis = System.currentTimeMillis()
            val nextPrayerTimeIndex: Int = binarySearchLeft(prayerTimeList!!, currentTimeMillis)
            when (nextPrayerTimeIndex) {
                (prayerTimeList?.size?.minus(1)) -> { //计算得出的下一次时间是午夜时间
                    val midnightPrayerTimeInfo = prayerTimeList!![nextPrayerTimeIndex] //取出午夜时间信息
                    val needShowPrayerTimeInfo = prayerTimeList!![nextPrayerTimeIndex - 1] // 取出Isha
                    mPrayerTimeName.text = needShowPrayerTimeInfo.prayerTimeName
                    if (is24HourFormat) {
                        mPrayerTime.text = Utils.to24HourFormat(
                            needShowPrayerTimeInfo.prayerTime,
                            Locale.getDefault()
                        )
                        mPrayerTimeAmPm.visibility = View.GONE
                    } else {
                        mPrayerTime.text = Utils.to12HourFormat(
                            needShowPrayerTimeInfo.prayerTime,
                            Locale.getDefault()
                        )
                        mPrayerTimeAmPm.visibility = View.VISIBLE
                        mPrayerTimeAmPm.text = needShowPrayerTimeInfo.timeType
                    }
                    // #1DBC37
        //                mPrayerTimeCount.setTextColor(Color.parseColor("#1DBC37"))
                    mDownTimer?.cancel()
                    mDownTimer = TimeCountDownTimer(
                        midnightPrayerTimeInfo.timestamp - currentTimeMillis,
                        1000,
                        1,
                        currentTimeMillis - needShowPrayerTimeInfo.timestamp
                    )
                    mDownTimer?.start()

                }
                -1 -> {
                    val needShowPrayerTimeInfo = prayerTimeList!![0] // 取出Fajr
                    mPrayerTimeName.text = needShowPrayerTimeInfo.prayerTimeName
                    if (is24HourFormat) {
                        mPrayerTime.text = Utils.to24HourFormat(
                            needShowPrayerTimeInfo.prayerTime,
                            Locale.getDefault()
                        )
                        mPrayerTimeAmPm.visibility = View.GONE
                    } else {
                        mPrayerTime.text = Utils.to12HourFormat(
                            needShowPrayerTimeInfo.prayerTime,
                            Locale.getDefault()
                        )
                        mPrayerTimeAmPm.visibility = View.VISIBLE
                        mPrayerTimeAmPm.text = needShowPrayerTimeInfo.timeType
                    }
        //                mPrayerTimeCount.setTextColor(Color.parseColor("#FF5B14"))
                    mDownTimer?.cancel()
                    mDownTimer = TimeCountDownTimer(
                        needShowPrayerTimeInfo.timestamp - currentTimeMillis,
                        1000,
                        0,
                        (currentTimeMillis - needShowPrayerTimeInfo.timestamp)
                    )
                    mDownTimer?.start()
                }
                else -> {
                    val nextPrayerTimeInfo = prayerTimeList!![nextPrayerTimeIndex]
                    mPrayerTimeName.text = nextPrayerTimeInfo.prayerTimeName
                    Logger.e("$nextPrayerTimeInfo")
                    if (is24HourFormat) {
                        mPrayerTime.text = Utils.to24HourFormat(
                            nextPrayerTimeInfo.prayerTime,
                            Locale.getDefault()
                        )
                        mPrayerTimeAmPm.visibility = View.GONE
                    } else {
                        mPrayerTime.text = Utils.to12HourFormat(
                            nextPrayerTimeInfo.prayerTime,
                            Locale.getDefault()
                        )
                        mPrayerTimeAmPm.visibility = View.VISIBLE
                        mPrayerTimeAmPm.text = nextPrayerTimeInfo.timeType
                    }
        //                mPrayerTimeCount.setTextColor(Color.parseColor("#FF5B14"))
                    mDownTimer?.cancel()
                    mDownTimer =
                        TimeCountDownTimer(
                            nextPrayerTimeInfo.timestamp - currentTimeMillis,
                            1000,
                            0,
                            0
                        )
                    mDownTimer?.start()
                }
            }
        } else {
            visibility = View.GONE
        }
    }

    override fun onAttachedToWindow() {
        Logger.e("============onAttachedToWindow=================")
        super.onAttachedToWindow()
        initData(true)
        registerLocationReceiver()
    }

    override fun onDetachedFromWindow() {
        Logger.e("============onDetachedFromWindow=================")
        super.onDetachedFromWindow()
        mDownTimer?.cancel()
        try {
            context.unregisterReceiver(mLocationReceiver)
        } catch (ignored: Exception) {

        }
    }

    private fun registerLocationReceiver() {
        val mFilter = IntentFilter()
        mFilter.addAction(Constants.ACTION_LOCATION_SUCCESS)
        mFilter.addAction(Constants.ACTION_UPDATED_PRAYER_TIME)
        mFilter.addAction(Intent.ACTION_TIME_CHANGED)
        mFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED)
        mFilter.addAction(Constants.ACTION_UNBIND)
        context.registerReceiver(mLocationReceiver, mFilter)
    }

    private val mLocationReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            Logger.e("action=$action")
            if (action == Constants.ACTION_LOCATION_SUCCESS) {
                val lat = intent.getStringExtra("LAT")
                val long = intent.getStringExtra("LONG")
                Logger.e("lat=$lat,long=$long")
                if (lat != "-999" && long != "-999") {
                    Settings.Global.putString(context.contentResolver, "LAT", lat)
                    Settings.Global.putString(context.contentResolver, "LONG", long)
                    initData(true)
                }
            } else if (action == Constants.ACTION_UPDATED_PRAYER_TIME
                || action == Intent.ACTION_TIME_CHANGED
                || action == Intent.ACTION_TIMEZONE_CHANGED
                || action == Constants.ACTION_UNBIND
            ) {  //祈祷设置发生改变，重新计算
                initData(true)
            }
        }
    }

    private fun calcPrayerTime(lat: Double, long: Double) {
        prayerTimesCoordinator.updateParameters(DateFormat.is24HourFormat(context))
        val timeZone: TimeZone = TimeZone.getDefault()
        val time = timeZone.rawOffset //获取时差，返回值毫秒
        prayerTimeList = prayerTimesCoordinator.getPrayerTimeData(
            lat,
            long,
            (time / 1000 / 60 / 60).toDouble()
        )
        Logger.e("calcPrayerTime $prayerTimeList")
    }


    //找到>=target最左的位置
    private fun binarySearchLeft(arr: MutableList<PrayerTimeInfo>, target: Long): Int {
        var left = 0
        var right = arr.size - 1
        var result = -1
        while (left <= right) {
            val middle = left + (right - left shr 1)
            if (arr[middle].timestamp >= target) {
                result = middle
                right = middle - 1
            } else {
                left = middle + 1
            }
        }
        return result
    }

    fun onPause() {
        mDownTimer?.cancel()
        mDownTimer == null
        try {
            context.unregisterReceiver(mLocationReceiver)
        } catch (ignored: Exception) {

        }
    }

    fun onResume(isShow: Boolean) {
        initData(isShow)
        registerLocationReceiver()
    }

    inner class TimeCountDownTimer(
        private val millisInFuture: Long,
        countDownInterval: Long,
        private val type: Int,
        private val offsetTime: Long
    ) : CountDownTimer(millisInFuture, countDownInterval) {

        override fun onTick(millisUntilFinished: Long) {
            Logger.e("onTick,millisUntilFinished=" + millisUntilFinished / 1000)
            if (type == 0) {
                val secs = millisUntilFinished / 1000
                mPrayerTimeCount.text =
                    String.format(
                        Locale.getDefault(), "%02d:%02d:%02d", secs / 3600, secs % 3600 / 60,
                        secs % 60
                    )
            } else {
                val secs = (millisInFuture - millisUntilFinished + offsetTime) / 1000
                mPrayerTimeCount.text =
                    String.format(
                        Locale.getDefault(), "%02d:%02d:%02d", secs / 3600, secs % 3600 / 60,
                        secs % 60
                    )
            }
        }

        override fun onFinish() {
            //停在界面倒计时或者正计时走完 更新下一次显示的UI
            initData(true)
        }

    }
}
